package com.srwl.mytx.widget;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.CommentAdapter_v1;
import com.srwl.mytx.domain.Comment;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CommentService;
import com.srwl.mytx.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CommentDialog extends BottomSheetDialog implements CommentAdapter_v1.CommentClickListener {
    private static final String TAG = "CommentDialog";
    private InteractionListener listener;
    private RecyclerView rv_commentList;
    private MaterialSmoothRefreshLayout refreshLayout;
    private ProgressBar progressBar;
    private View leftLayout;
    private TextView tv_commentCount;
    private CommentAdapter_v1 commentAdapter;
    private List<Comment> commentList = new ArrayList<>();
    private Map praiseRecord;//被我点赞记录
    private Map commentPraiseSize;//点赞数量
    private int page = 1;
    private boolean hasNextPage;
    private Topic topic;

    public CommentDialog(@NonNull Context context) {
        super(context);
    }

    public CommentDialog(@NonNull Context context, Topic topic, final InteractionListener listener) {
        super(context, R.style.BottomDialog_v1);
        this.listener = listener;
        this.topic = topic;
        init(context);
    }

    private void init(@NonNull Context context) {
        setContentView(R.layout.layout_comment_dialog);
        addScrollListener();
        progressBar = findViewById(R.id.progress_bar);
        rv_commentList = findViewById(R.id.rv_comment_list);
        refreshLayout = findViewById(R.id.refresh_layout);
        leftLayout = findViewById(R.id.left_layout);
        tv_commentCount = findViewById(R.id.tv_comment_count);
        leftLayout.setOnClickListener(v -> dismiss());
        if (topic.getCommentSize() == null) {
            tv_commentCount.setText("暂无评论");

        } else {
            tv_commentCount.setText("共 " + topic.getCommentSize() + " 条评论");
        }
        commentAdapter = new CommentAdapter_v1(context, commentList, this);
        rv_commentList.setLayoutManager(new LinearLayoutManager(context));
        rv_commentList.setAdapter(commentAdapter);
        initRefreshLayout();
        loadData(true);
    }

    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(true);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.verticalMargin = Utils.dpToPx(40, getContext());
        getWindow().setAttributes(attributes);
    }

    public void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            Toast.makeText(getContext(), getContext().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topic.getId());
        info.put("uId", UserProfileManager.getInstance().getLoginUserInfo().getuId());
        info.put("page", page);
        info.put("size", 10);
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .getComment(info)
                .enqueue(new Callback<CommonResult>() {

                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {

                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());

                            return;
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();

                        JSONObject pageInfo = jsonObject.getJSONObject("comments");
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(getContext())), 1000);
                        }
                        List<Comment> comments = pageInfo.getJSONArray("list").toJavaList(Comment.class);
                        Log.d(TAG, jsonObject.toJSONString());
                        if (page == 1 && comments.size() != 0) {
                            //以此来判别那些评论是被我点过赞
                            if (jsonObject.containsKey("praiseRecord")) {
                                praiseRecord = JSONObject.parseObject(jsonObject.get("praiseRecord").toString(), Map.class);
                            }
                            if (jsonObject.containsKey("commentPraiseSize")) {
                                commentPraiseSize = JSONObject.parseObject(jsonObject.get("commentPraiseSize").toString(), Map.class);
                            }


                        }
                        checkIsPraise(comments);
                        setupPraiseSize(comments);

                        commentList.addAll(comments);
                        commentAdapter.notifyDataSetChanged();
                        page++;

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, t.getMessage());

                    }
                });
    }


    /**
     * 设置评论的点赞数量
     *
     * @param comments
     */
    void setupPraiseSize(List<Comment> comments) {
        if (commentPraiseSize == null || commentPraiseSize.size() == 0) {
            return;
        }
        for (Object o : commentPraiseSize.keySet()) {
            for (Comment comment : comments) {
                if (comment.getId().equals(o)) {
                    comment.setPraiseSize(Integer.valueOf(commentPraiseSize.get(o).toString()));
                }
            }
        }
    }


    /**
     * 检查哪些评论被我点过赞，点过赞的给与标记
     *
     * @param comments
     */
    void checkIsPraise(List<Comment> comments) {
        //先进行非空判断，然后遍历，把被我赞过的评论，做好标记
        if (praiseRecord == null || praiseRecord.size() == 0) {
            return;
        }
        for (Object o : praiseRecord.keySet()) {
            for (Comment comment : comments) {
                if (comment.getId().equals(o)) {
                    comment.setHadPraise(true);
                }
            }
        }
    }


    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    @Override
    public void commentItemLongClick(int position) {

    }

    @Override
    public void avatarClick(User targetUser) {

    }

    @Override
    public void commentItemClick(Comment parentComment, int position) {

    }

    @Override
    public void childCommentItemClick(Comment parentComment, int position, User rePlyTarget) {

    }

    @Override
    public void addCommentPraise(Comment targetComment, int position) {
        if (!Helper.getInstance().isNetworkConnected()){
            Toast.makeText(getContext(), getContext().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topic.getId());
        info.put("commentId", targetComment.getId());
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .commentPraise(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 添加评论点赞完成");

//                                commentList.get(position).setHadPraise(true);
//                                commentAdapter.notifyItemChanged(position);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    @Override
    public void removeCommentPraise(Comment targetComment, int position) {
        if (!Helper.getInstance().isNetworkConnected()){
            Toast.makeText(getContext(), getContext().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topic.getId());
        info.put("commentId", targetComment.getId());
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .removeCommentPraise(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 去除评论点赞完成");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    @Override
    public void clearCommentTarget() {

    }

    private void addScrollListener() {

        View view1 = getDelegate().findViewById(R.id.design_bottom_sheet);
        final BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(view1);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    dismiss();
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                Log.d(TAG, "onSlide:滑动  " + slideOffset);

                Log.d(TAG, "onSlide: bottomSheet底部" + bottomSheet.getBottom());
            }
        });
    }

    public interface InteractionListener {

        void onCommentItemClick(Comment clickComment);
    }
}
